package com.singlever;

import com.ChessUtils.ChessUtil;
import com.ChessUtils.JugWinLoseUtil;
import com.beans.Chess;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author acoffee
 * @create 2021-08-12 19:20
 */
public class SingleButtonService {
    // 换边(黑棋先行)
    private char playSides = 'B';
    //储存棋子的数组
    private List<Chess> chesses = new ArrayList();
    //记录棋子的数量
    private int chessCount = 0;
    //是否胜利
    private boolean Win = false;


    public void Click(SingleGoBangView singleGoBangView, Pane pane, int PaneLength, int SceneLength) {

        //给画板绑定鼠标点击事件
        pane.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                //获取到鼠标点击的真实坐标(x,y)
                int x = ((int) event.getX() - PaneLength + PaneLength / 2) / PaneLength;
                int y = ((int) event.getY() - PaneLength + PaneLength / 2) / PaneLength;

                //判断是否胜利了
                if (Win || !JugWinLoseUtil.ChessLegal(x, y, PaneLength, SceneLength,chessCount,chesses)) {
                    return;
                }


                Chess chess;
                Circle circle;
                //创建圆圈对象
                if (playSides == 'B') {
                    circle = new Circle(x * PaneLength + PaneLength,
                            y * PaneLength + PaneLength, 10, Color.BLACK);
                    chess = new Chess(x, y, Color.BLACK);

                } else {
                    circle = new Circle(x * PaneLength + PaneLength,
                            y * PaneLength + PaneLength, 10, Color.WHITE);
                    chess = new Chess(x, y, Color.WHITE);
                }

                chesses.add(chess);
                chessCount++;

                //将圆圈放到画板上
                pane.getChildren().add(circle);

                if (JugWinLoseUtil.WinGame(chess,chessCount,chesses)) {

                    String str = playSides == 'B' ? "黑棋获胜!" : "白棋获胜!";

                    //胜利提示
                    ChessUtil.getUpWindows(singleGoBangView, Alert.AlertType.CONFIRMATION, str, "点击确定关闭对话框");

                    Win = true;
                }
                //换边
                playSides = JugWinLoseUtil.ChangeSides(playSides);
            }
        });
    }


    //为新局按钮绑定功能
    public void newGameButtonAction(SingleGoBangView singleGoBangView, Button NewGameBtn, Pane pane, Button btnBack, Button btnNext, Button btnRegameExit) {
        NewGameBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                boolean isNew = ChessUtil.getUpWindows(singleGoBangView, Alert.AlertType.CONFIRMATION, "新局", "点击确认，开启新局");

                if (isNew) {
                    initializeChess(pane);
                    pane.getChildren().removeAll(btnBack, btnNext, btnRegameExit);
                }
            }
        });
    }

    //为保存棋谱添加功能
    public void SaveGameBtnAction(Button SaveGameBtn, SingleGoBangView gobang) {

        SaveGameBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                //让文件选择器，在本窗体弹出
                File file = ChessUtil.FileChoose("保存棋谱").showSaveDialog(gobang);

                if (file == null) {
                    return;
                }

                for (Chess chess : chesses) {
                    String context = chess.getX() + "," + chess.getY() + "," + chess.getColor();
                    ChessUtil.write(context, file);
                }
            }
        });
    }

    //为打谱按钮添加功能
    public void ReGameBtnAction(SingleGoBangView gobang, Button ReGameBtn, Pane pane, Button btnBack, Button btnNext, Button btnRegameExit, int PaneLength) {

        ReGameBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                //清空棋盘上的棋子
                initializeChess(pane);

                //只要打谱就不能落子的功能
                Win = true;

                //在窗口下选择某一个文件
                File file = ChessUtil.FileChoose("打开棋谱！").showOpenDialog(gobang);

                //如果没有选中文件，直接结束
                if (file == null) {
                    return;
                }

                ArrayList<Chess> list = new ArrayList<>();

                List<String> strs = ChessUtil.read(file);
                for (String str : strs) {
                    //将x轴、y轴、以及棋子的颜色从字符串中分离出来
                    String[] temp = str.split(",");
                    Chess chess = new Chess(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Color.valueOf(temp[2]));
                    list.add(chess);
                }

                //不包含按钮就添加，有了就不添加，如果重复添加会报异常
                if (!pane.getChildren().contains(btnNext)) {
                    //点击打谱过后就出现打谱操作按钮
                    pane.getChildren().addAll(btnBack, btnNext, btnRegameExit);
                }

                //将打谱的三个功能键绑定给打谱按钮
                btnNextAction(gobang, btnNext, list, PaneLength, pane);
                btnBackAction(gobang, btnBack, pane);
                btnRegameExitAction(gobang, btnRegameExit, pane, btnBack, btnNext);

            }
        });
    }

    //为打谱下一步功能键添加功能
    public void btnNextAction(SingleGoBangView singleGoBangView, Button btnNext, ArrayList<Chess> list, int PaneLength, Pane pane) {
        btnNext.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                if (chessCount == list.size()) {
                    ChessUtil.getUpWindows(singleGoBangView, Alert.AlertType.WARNING, "警告！", "棋谱中的棋子已经取完了！");
                    return;
                }
                Chess chess = list.get(chessCount);
                Circle circle = new Circle(chess.getX() * PaneLength + PaneLength,
                        chess.getY() * PaneLength + PaneLength, 10, chess.getColor());

                //将棋谱中的棋子加入到棋盘中
                pane.getChildren().add(circle);
                chessCount++;
            }
        });
    }

    //为打谱上一步功能键添加功能
    public void btnBackAction(SingleGoBangView singleGoBangView, Button btnBack, Pane pane) {
        btnBack.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (chessCount == 0) {
                    ChessUtil.getUpWindows(singleGoBangView, Alert.AlertType.WARNING, "警告", "棋子已经没有了，不能上一步！");
                    return;
                } else {
                    pane.getChildren().remove(pane.getChildren().size() - 1);
                    chessCount--;
                }

            }
        });
    }

    //为打谱退出功能键添加功能
    public void btnRegameExitAction(SingleGoBangView singleGoBangView, Button btnRegameExit, Pane pane, Button btnBack, Button btnNext) {
        btnRegameExit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                boolean isExit = ChessUtil.getUpWindows(singleGoBangView, Alert.AlertType.CONFIRMATION, "退出", "点击确认，即可退出！");
                if (isExit) {
                    initializeChess(pane);
                    pane.getChildren().removeAll(btnBack, btnNext, btnRegameExit);
                }
            }
        });
    }

    //为悔棋按钮添加功能
    public void RegretBtnAction(Pane pane, Button RegretBtn) {
        RegretBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (!Win && chesses.size() > 0) {
                    pane.getChildren().remove(pane.getChildren().size() - 1);
                    playSides = playSides == 'B' ? 'W' : 'B';
                    chesses.remove(chesses.size() - 1);
                    chessCount--;
                }
            }
        });
    }

    //为退出功能添加功能
    public void ExitBtnAcition(SingleGoBangView singleGoBangView, Button ExitBtn) {
        ExitBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                boolean isExit = ChessUtil.getUpWindows(singleGoBangView, Alert.AlertType.CONFIRMATION, "退出", "点击确定,即可退出游戏");
                if (isExit) {
                    System.exit(0);
                }

            }
        });
    }

    //初始化棋子
    public void initializeChess(Pane pane) {
        pane.getChildren().removeIf(new Predicate<Object>() {
            @Override
            public boolean test(Object t) {
                return t instanceof Circle;
            }
        });

        //将棋子容器初始化
        chesses = new ArrayList<Chess>();
        chessCount = 0;
        Win = false;
        playSides = 'B';
    }
}
